package cn.zy.amyan.client;

import cn.zy.amyan.client.handler.ClientInitializer;
import cn.zy.amyan.core.base.RequestData;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author 子言
 * @date 2024/5/5 下午 17:04
 */
public class AyClient {

	private Channel channel;
	private EventLoopGroup worker;

	public void start(String host, int port) {
		try {
			doStart(host, port);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void doStart(String host, int port) throws InterruptedException {
		this.worker = new NioEventLoopGroup();
		Bootstrap client = new Bootstrap();
		client.group(this.worker)
				.channel(NioSocketChannel.class)
				.handler(new ClientInitializer());
		ChannelFuture future = client.connect(host, port).sync();
		this.channel = future.channel();
	}

	public void close() {
		if(null != this.channel && this.channel.isActive()) {
			this.channel.close();
		}
		if(null != this.worker && !this.worker.isShutdown()) {
			this.worker.shutdownGracefully();
		}
	}

	public void sendMsg(RequestData request) {
		this.channel.writeAndFlush(request);
	}
	
}
